<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
  <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
  <style type="text/css">
    .highlight { display: block; background-color: #ddd; }
  </style>
  <script type="text/javascript">
    function highlight() {
      document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
    }
  </script>
</head>
<body onload="prettyPrint(); highlight();">
  <pre class="prettyprint lang-js">/*
 * Copyright (c) 2016 VUI(https://git.oschina.net/durcframework/vui) All rights reserved.
 */

;(function(){

var ruleName = 'aj-rules';

<span id='VUI-Form'>/**
</span> * 表单控件&lt;br&gt;
 * &lt;pre&gt;
form = new VUI.Form({
	formId:'ff'
});
 * &lt;/pre&gt;
 * @class VUI.Form
 * @extends VUI.Common
 */
VUI.Class('Form',{
	OPTS:{
<span id='VUI-Form-cfg-form'>		/**
</span>		 * @cfg {String} form表单ID
		 */
		formId:''
<span id='VUI-Form-cfg-method'>		/**
</span>		 * @cfg {String} 表单请求方式
		 */
		,method:'POST'
	}
	
	// ----- 事件注释 -----
	
<span id='VUI-Form-event-onSubmit'>	/**
</span>	 * @event onSubmit 在请求加载数据之前触发。返回false可以停止该动作。
	 * @param {Object} data 请求数据
	 */
	 
<span id='VUI-Form-event-onLoadSuccess'>	/**
</span>	 * @event onLoadSuccess 在表单数据加载完成后触发。
	 * @param {Object} data 响应数据
	 */
	 
<span id='VUI-Form-event-success'>	/**
</span>	 * @event success 在表单提交成功以后触发。
	 * @param {Object} data 响应数据
	 */
	 
<span id='VUI-Form-event-onLoadError'>	/**
</span>	 * @event onLoadError 在表单数据加载出现错误的时候触发。
	 * @param {Object} e e.xhr XMLHttpRequest对象,e.status 响应状态,e.error 错误信息
	 */
	 
<span id='VUI-Form-event-onSubmitError'>	/**
</span>	 * @event onSubmitError 在表单数提交数据失败时触发。
	 * @param {Object} e e.xhr XMLHttpRequest对象,e.status 响应状态,e.error 错误信息
	 */
	
<span id='global-method-constructor'>	/**
</span>	 * 构造函数
	 * @constructor
	 * @ignore
	 */
	,init:function(opts) {
		this._super(opts);
		
		this.$form = $('#'+this.opts.formId);
		
		this.addExtMethod();
		
		this.parseForm(this.$form);
	}
<span id='VUI-Form-method-validate'>	/**
</span>	 * 做表单字段验证，当所有字段都有效的时候返回true.改方法会显示所有字段的错误信息&lt;br&gt;
	 * 如果只显示一个错误信息,可以调用check()方法
	 * @return {Boolean} 当所有字段都有效的时候返回true
	 */
	,validate:function() {
		var ret = true;
		this.$els.each(function(){
			var r = $(this).validate();
			if(!r) {
				ret = false;
			}
		});	
		return ret;
	}
<span id='VUI-Form-method-check'>	/**
</span>	 * 做表单字段验证，当第一个字段验证失败则返回false,所有字段验证成功返回true
	 * @return {Boolean} 当所有字段都有效的时候返回true
	 */
	,check:function() {
		var ret = true;
		this.$els.each(function(){
			ret = $(this).validate();
			if(!ret) {
				ret = false;
				return false;
			}
		});	
		return ret;
	}
<span id='VUI-Form-method-submit'>	/**
</span>	 * 执行提交操作
	 * @param {Object} opts 提交参数
	 * &lt;pre&gt;
	 * 执行提交操作，该选项的参数是一个对象，它包含以下属性：
		url：请求的URL地址。
		onSubmit: 提交之前的回调函数。
		success: 提交成功后的回调函数。
		
		var url = 'http://localhost:8087/emptyProject/listEasyuiOrderInfo_backuser.do';
		form2.submit({
			url:url
			,onSubmit: function(){
				return this.validate();	// 返回false终止表单提交
			}
			,success: function(data){
				console.log('submit success.');
				console.log(data);
			}
	
		});
	 * &lt;/pre&gt;
	 */
	,submit:function(opts) {
		var onSubmit = opts.onSubmit || this.opts.onSubmit;
		var data = opts.data || this.getData();
		if(onSubmit) {
			var ret = onSubmit.call(this,data);
			if(ret === false) {
				return;
			}
		}
		this.fire('BeforeSubmit',data);
		this.doSubmit(opts,data);
	}
<span id='VUI-Form-method-doSubmit'>	/**
</span>	 * @private
	 */
	,doSubmit:function(opts,data) {
		var that = this;
		var method = this.$form.attr('method') || this.opt('method');
		$.ajax({
			type: method,
			url: opts.url,
			traditional:true,
			dataType: 'json',
			data:data,
			success: function(data, textStatus, jqXHR){
				var success = opts.success || that.opts.success;
				success &amp;&amp; success(data);
			},
			error:function(XMLHttpRequest, textStatus, errorThrown){
				that.fire('SubmitError',{xhr:XMLHttpRequest, status:textStatus, error:errorThrown});
			}
		});
	}
<span id='VUI-Form-method-load'>	/**
</span>	 * @param {Object} data 读取记录填充到表单中。数据参数可以是一个字符串或一个对象类型，如果是字符串则作为远程URL，否则作为本地记录。&lt;br&gt;
	 * &lt;pre&gt;
form2.load({
	single:3
	,t1:'t1text'
	,t2:'t2aaaa'
	,check:[1,2]
	,radio:2
});

form2.load(url);
	 * &lt;/pre&gt;
	 */
	,load:function(data) {
		if(typeof data === 'string') {
			var url = data;
			this.loadRemoteData(url);
		}else{
			this.loadData(data);
		}
	}
<span id='VUI-Form-method-setData'>	/**
</span>	 * 同load(data)
	 */
	,setData:function(data) {
		this.load(data);
	}
<span id='VUI-Form-method-loadRemoteData'>	/**
</span>	 * @private
	 */
	,loadRemoteData:function(url) {
		var that = this;
		
		var ret = this.fire('BeforeLoad');
		if(ret === false) {
			return;
		}
		
		$.ajax({
			type: 'GET',
			url: url,
			traditional:true,
			dataType: 'json',
			success: function(data, textStatus, jqXHR){
				that.fire('LoadSuccess',data);
				that.loadData(data);
			},
			error:function(XMLHttpRequest, textStatus, errorThrown){
				that.fire('LoadError',XMLHttpRequest, textStatus, errorThrown);
			}
		});
	}
<span id='VUI-Form-method-loadData'>	/**
</span>	 * @private
	 */
	,loadData:function(data) {
		this.clear();
		for(var name in data) {
			var val = data[name];
			var $el = this.$form.find('[name=&quot;'+name+'&quot;]');
			
			$el.each(function(){
				var _$el = $(this);
				if(_$el.is(':radio') || _$el.is(':checkbox')) {
					_$el.prop('checked',false);
					var elVal = _$el.val();
					
					if($.isArray(val)) {
						for(var i=0, len=val.length;i&lt;len; i++) {
							if(elVal == val[i]){
								_$el.prop('checked',true);
							}
						}
					}else{
						_$el.prop('checked',elVal == val);
					}
					
				}else {
					_$el.val(val);
				}
				
			});
		}
	}
<span id='VUI-Form-method-clear'>	/**
</span>	 * 清除表单中的值,清除错误信息
	 */
	,clear:function() {
		this.$els.each(function(){
			var _$el = $(this);
			if(_$el.is(':radio') || _$el.is(':checkbox')) {
				this.checked = false;
			}else{
				this.value = '';
			}
			
			var msg = _$el.data('msg');
			if(msg) {
				msg.text('');
			}
			
		});	
	}
<span id='VUI-Form-method-reset'>	/**
</span>	 * 重置表单
	 */
	,reset:function() {
		var form = this.form;
		if(form &amp;&amp; form.reset) {
			form.reset();
		}else{
			this.clear();
		}
	}
<span id='VUI-Form-method-getData'>	/**
</span>	 * 获取表单数据,如果有fieldName参数则返回表单对应的值&lt;br&gt;
	 * var id = form.getData('id') 等同于 var id = form.getData().id;
	 * @param {String} fieldName 
	 * @return {Object} 返回JSON对象,如果有fieldName参数,则返回对应的值
	 */
	,getData:function(fieldName) {
		var that = this;
		var data = {};
		
		this.$els.each(function(){
			var value = that._getInputVal($(this));
			if(value) {
				var name = this.name;
				var dataValue = data[name];
				if(dataValue) {
					if($.isArray(dataValue)) {
						dataValue.push(value);
					}else{
						data[name] = [dataValue,value];
					}
				}else{
					data[name] = value;
				}
			}
		});
		
		if(typeof fieldName === 'string') {
			return data[fieldName];
		}

		return data;
	}
	,getFormData:function($form) {
		var data = {};
		var dataArr = $form.serializeArray();
		for(var i=0, len=dataArr.length;i&lt;len; i++) {
			var item = dataArr[i];
			var name = item.name;
			var itemValue = item.value;
			var dataValue = data[name];
			
			if(dataValue) {
				if($.isArray(dataValue)) {
					dataValue.push(itemValue);
				}else{
					data[name] = [dataValue,itemValue];
				}
			}else{
				data[name] = itemValue;
			}
			
		}
		
		return data;
	}
	,_getInputVal:function($input) {
		if($input.is(&quot;:radio&quot;) || $input.is(&quot;:checkbox&quot;)) {
			if($input.is(':checked')) {
				return $input.val();
			}
		}else{
			return $input.val(); 
		}
	}
<span id='VUI-Form-method-parseForm'>	/**
</span>	 * @private
	 */
	,parseForm:function($form) {
		var that = this;
		this.form = $form[0];
		this.$els = $form.find('input,select,textarea');
		this.$els.each(function(){
			that.doParse($(this));
		});
	}
<span id='VUI-Form-method-doParse'>	/**
</span>	 * @private
	 */
	,doParse:function($el) {
		var rules = $el.attr('rules');
		rules = eval('('+rules+')') || [];
		$el.addRules(rules);
	}
<span id='VUI-Form-method-addExtMethod'>	/**
</span>	 * @private
	 */
	,addExtMethod:function() {
		jQuery.fn.extend({
			addRules:function(rules) {
				rules = rules || [];
				this.data(ruleName,rules);
			}
			,buildRules:function() {
				var rules = this.attr('rules');
				rules = eval('('+rules+')') || [];
				this.addRules(rules);
			}
			,validate:function() {
				var passValidate = this.attr('passValidate');
				if(passValidate == &quot;true&quot;) {
					return true;
				}
				var rules = this.data(ruleName) || [];
				var value = this.getValue();
				for(var i=0,len=rules.length; i&lt;len; i++) {
					var opt = rules[i];
					this._initMsgId(opt);
					var validate = new VUI.Validate(opt);
					var ret = validate.validate(value);
					if(!ret) {
						return false;
					}
				}
				
				return true;
			}
			,_initMsgId:function(opt) {
				var msgId = opt.msgId || this.attr('msgId');
				if(!msgId) {
					msgId = 'ajform_msg_' + VUI.getId();
					this.parent().append('&lt;span id=&quot;'+msgId+'&quot;&gt;&lt;/span&gt;');
				}
				this.data('msg',$('#'+msgId));
				opt.msgId = msgId;
			}
			,getValue:function() {
				return this.val();
			}
		});
		
		this.addExtMethod = function(){}
	}
},VUI.Common);


})();</pre>
</body>
</html>
